package com.hsc.www.mybatis.soEasy.ee.crudMapper;


import com.hsc.www.mybatis.soEasy.ee.rr.BaseExample;
import com.hsc.www.mybatis.soEasy.ee.page.Page;

import java.io.Serializable;
import java.util.List;

public interface SelectMapper<ID extends Serializable, Entity, Example extends BaseExample> extends SelectBaseMapper<ID, Entity, Example> {

    default int countByEntity(Entity entity) {
        return countByEntity(entity, getDefaultStrategy());
    }

    default Entity selectByPrimaryKey(ID id) {
        return selectByPrimaryKey(id, isExcludeBlobs());
    }

    default List<Entity> selectByExample(Example example) {
        return selectByExample(example, isExcludeBlobs());
    }

    default Entity selectOneByExample(Example example, boolean excludeBlobs) {
        List<Entity> list = selectByExample(example, excludeBlobs);
        return assertOne(list);
    }

    default Entity selectOneByExample(Example example) {
        return selectOneByExample(example, isExcludeBlobs());
    }


    default List<Entity> selectByEntity(Entity entity) {
        return selectByEntity(entity, getDefaultStrategy(), isExcludeBlobs());
    }

    default Entity selectOneByEntity(Entity entity, boolean excludeBlobs) {
        List<Entity> list = selectByEntity(entity, getDefaultStrategy(), excludeBlobs);
        return assertOne(list);
    }

    default Entity selectOneByEntity(Entity entity) {
        return selectOneByEntity(entity, isExcludeBlobs());
    }

    default Page<Entity> selectPageByExample(Example example, Page page, boolean excludeBlobs) {
        page.getPageHelper().preProcess(page);
        List<Entity> entityList = selectByExample(example, excludeBlobs);
        page.getPageHelper().postProcess(page, entityList);
        return page;
    }

    default Page<Entity> selectPageByExample(Example example, Page page) {
        return selectPageByExample(example, page, isExcludeBlobs());
    }

    default Page<Entity> selectPageByEntity(Entity entity, Page page, boolean excludeBlobs) {
        page.getPageHelper().preProcess(page);
        List<Entity> entityList = selectByEntity(entity, getDefaultStrategy(), excludeBlobs);
        page.getPageHelper().postProcess(page, entityList);
        return page;
    }

    default Page<Entity> selectPageByEntity(Entity entity, Page page) {
        return selectPageByEntity(entity, page, isExcludeBlobs());
    }


    static <T> T assertOne(List<T> list) {
        if (list == null || list.isEmpty()) {
            return null;
        } else if (list.size() == 1) {
            return list.get(0);
        } else {
            throw new RuntimeException("从数据库中查询出多条数据。");
        }
    }


}
